<template>
  <div class="layout">
    <Layout>
      <Sider  ref="sideLeft" hide-trigger collapsible :width="220" :collapsed-width="78" v-model="isCollapsed" :style="{background: '#515a6e',height: '100%',color:'#eee',overflow: 'hidden'}">
        <!--左侧导航展开-->
        <Menu width="auto" height="100%"  ref='menu' style="color: #eee" theme="dark" :class="menuitemClasses" accordion @on-select="slectName" :active-name="activeName" :open-names='openName'>

          <div style="height: 16px;">
            <!-- <span style="width:100%;line-height: 64px;text-align: center;font-size: 26px;" v-if="showLogo">瓜钱包 - 管理系统</span>
            <span style="width:100%;line-height: 64px;text-align: center;font-size: 26px;" v-if="!showLogo">瓜</span> -->
          </div>
           <MenuItem v-for="(item,index) in menuList" :key="index" :name="index+1"  v-if="item.name=='工作台'" :to="item.href">
             <Icon :type="item.icon"></Icon>
             <span class="menu-item-title">{{item.name}}</span>
          </MenuItem>
          <Submenu v-for="(item,index) in menuList" :key="index" :name="index+1"  v-if="item.name!='工作台'">
            <template slot="title">
              <Icon :type="item.icon"></Icon>
              <span class="menu-item-title">{{item.name}}</span>
            </template>
            <div v-for="(obj,idx) in item.nextSubs" :key="idx">
              <MenuItem v-if="obj.nextSubs.length === 0" :name="(index+1)+'-'+idx" :to="obj.href">{{obj.name}}</MenuItem>
              <menu-tree v-else :menuItem="obj" :parentId="(index+1)+'-'+idx"></menu-tree>
            </div>
          </Submenu>
        </Menu>
      </Sider>
      <div class="dropdown-hide" :class="dropdownToggle">
        <Dropdown placement="right-start" v-for="(item,index) in menuList" :key="index" @on-click="linkPage">
          <a href="javascript:void(0)">
            <Icon :type="item.icon" size="22"></Icon>
          </a>
          <DropdownMenu slot="list">
            <div v-for="(obj,idx) in item.nextSubs" :key="idx">
              <DropdownItem v-if="obj.nextSubs.length === 0" :name="obj.href">{{obj.name}}</DropdownItem>
              <sider-tree v-if="obj.nextSubs.length !== 0" :menuItem="obj"></sider-tree>
            </div>
          </DropdownMenu>
        </Dropdown>
      </div>
      <Layout>
        <Header>
          <Menu mode="horizontal">
            <div class="collapse-btn" style="width:28px;" >
              <Icon @click.native="collapsedSider" :class="rotateIcon" :style="{margin: '0 20px',color:'#000'}" type="md-menu" size="24"></Icon>
            </div>
            <div class="layout-nav">
              <Dropdown style="margin-right: 40px;"  @on-click="handleClick">
              <span class="account"> {{account}}</span>
              <Icon type="ios-contact-outline" size="24"></Icon>
                <DropdownMenu slot="list">
                  <DropdownItem name="logout">退出登录</DropdownItem>
                </DropdownMenu>
              </Dropdown>
              <!--<MenuItem name="5">-->
                <!--<Icon type="ios-exit-outline" size="24"></Icon>-->
              <!--</MenuItem>-->

            </div>
             <div style="float:right;margin-right:16px;" >
              <span>平台风控余额：<span :class="rests">{{toYuan(restMoney)}}</span></span>
              <span style="color:#2d8cf0;margin-left:3px;cursor:pointer;" @click="show = true">充值</span>
            </div>
          </Menu>
          <div class="tag-nav-wrapper">
            <tags-nav  @activeName="getactiveName"></tags-nav>
          </div>
        </Header>
        <Content :style="{padding: '30px 20px',overFlow:'auto'}">
          <Layout>
            <router-view @menulist="getLeftMenuListS" :nameSelect='name'/>
          </Layout>
        </Content>
      </Layout>
    </Layout>
    <Modal
        v-model="show"
        title="充值"
        width="680px"
        :footer-hide="true"
        :closable="false"
        :mask-closable="false"
     >
      <Form ref="formRole" :model="formRole" :rules="rules"  :label-width="110">
        <FormItem label="商户名称">
          <Input v-model.trim="formRole.name"  style="width: 300px" disabled/>
        </FormItem>
         <FormItem label="账户余额(元)">
          <Input v-model.trim="formRole.restMoney" style="width: 300px" disabled/>
        </FormItem>
         <FormItem label="充值方式">
          <Input v-model.trim="formRole.payWay" style="width: 300px" disabled/>
        </FormItem>
        <FormItem label="银行卡号" prop="bank_card">
          <Input v-model.trim="formRole.bank_card"  placeholder="请输入银行卡号" style="width: 300px" :maxlength="20" clearable/>
        </FormItem>
        <FormItem label="汇款公司" prop="company">
          <Input v-model.trim="formRole.company"  placeholder="请输入汇款公司" style="width: 300px" :maxlength="25" clearable/>
        </FormItem>
        <FormItem label="充值金额(元)" prop="amount">
          <Input v-model.trim="formRole.amount"  placeholder="请输入充值金额" style="width: 300px" :maxlength="7" clearable/>
        </FormItem>
        <FormItem label="上传凭证" prop="image">
           <Upload
            :action = "uploadUrl"
            :show-upload-list="false"
            name="uploadFile"
            :before-upload="handleUpload"
            :on-success="handleSuccess"
            accept="image/*"
            :on-error='handleError'
            v-model="formRole.image"
            :headers="headers"
            >
            <div class="picture">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <Icon type="ios-add" size="80" v-else></Icon>
            </div>
          </Upload>
           <p v-if="imageUrl" style="cursor:pointer;color:#2d8cf0;font-size:14px;" @click="visible = true;">查看图片</p>
        </FormItem>
      <div style="text-align:right">
        <Button @click="show = false;imageUrl='';resetValidate('formRole');" style="margin-right:2px">取消</Button>
        <Button type = "primary" @click="submitModal">确定</Button>
      </div>
      </Form>
      </Modal>
  </div>
</template>

<script>
  import TagsNav from './template/tags-nav'
  import menuTree from './template/menuTreeTemplate'
  import siderTree from './template/siderTreeTemplate'
  import {zeroType,bankType} from '../js/rules'
  import store from '../store'
  export default {
    name: 'layout',
    components:{
      TagsNav,
      menuTree,
      siderTree
    },
    data () {
      return {
        showLogo: true,
        isCollapsed: false,
        /*tag: {
          'title': '工作台',
          'path': '/work'
        },*/
        parentId: '',
        account:'',
        menuList:[],
        name:'',
        activeName:'',
        openName:[],
        restMoney:'1002',
        show:false,
        visible:false,
        formRole:{},
        uploadUrl: `${this.$http.defaults.baseURL}/merchant/photo`,
        headers:{
          "ua":'1;1.0.0;API0;web',
          "Authorization":'Authorization'
        },
        imageUrl:'',
        rules:{
          bank_card: [
            { required: true, message: '请输入正确的银行卡号', trigger: 'blur',validator:bankType}
          ],
          company: [
            { required: true, message: '请输入汇款公司', trigger: 'blur'}
          ],
          amount: [
            { required: true, message: '请输入正整数', trigger: 'blur',validator:zeroType}
          ],
          image: [
            { required: true, message: '请选择图片', trigger: 'blur' }
          ],
        },
      }
    },
    watch:{
      menuList(res){
        // console.log(res)
      },
    //  isFollow(newStore){
    //     console.log(newStore,'dddd');
    //     this.show=newStore
    //   }
    },
    computed: {
  //  isFollow () {
  //    return this.$store.state.show;　　//需要监听的数据
  // },
    rests(){
     let res = this.toYuan(this.restMoney) > 500 ? '' : 'activeRest'
     return res
    },
      rotateIcon () {
        return [
          'menu-icon',
          this.isCollapsed ? 'rotate-icon' : ''
        ];
      },
      menuitemClasses () {
        return [
          'menu-item',
          this.isCollapsed ? 'collapsed-menu' : ''
        ]
      },
      dropdownToggle () {
        return [
          this.isCollapsed ? 'dropdown-show' : ''
        ]
      }
    },
    created(){
      //this.getLeftMenuList();
      this.menuList = JSON.parse(sessionStorage.getItem('mu'))
    },
    mounted(){
      // console.log(this.$store.state.show,'ss')
      // this.show = this.$store.state.show
       this.$post('/sys/user/info')
        .then((res) => {
          if(res.code === 0){
            this.account=res.data.userNameCN;
            sessionStorage.setItem('adminid',res.data.id)
            // console.log(JSON.parse(res.data.menus))
            // this.menuList = JSON.parse(res.data.menus);
          }
        })
    },
    methods: {
     slectName(name){
       this.name = name;
      //  console.log(name,'选中的name');
     },
     getactiveName(activeName){
       // console.log(activeName,'activeName');
       this.activeName = activeName;
       this.openName = activeName.indexOf('-') != -1 ? activeName.split('-')[0] : activeName;
       this.openName = [ parseInt(this.openName) ]
      this.$nextTick(()=>{
        this.$refs.menu.updateOpened();
        this.$refs.menu.updateActiveName();
      })
     },
      getLeftMenuList(data) {
        //左侧导航栏
        this.$post('/sys/user/menu')
          .then((res) => {
            if(res.code === 0){
              // console.log( JSON.parse(res.data.menus),'menus')
              sessionStorage.setItem('mu',res.data.menus)
              this.menuList = JSON.parse(res.data.menus);
            }
          })
      },
      getLeftMenuListS(){
        // console.log(sessionStorage.getItem('mu'),'sessMu')
        this.menuList = JSON.parse(sessionStorage.getItem('mu'));
      },
      handleClick(){
        this.$store.state.tagNavList=[];
        this.$post('/sys/user/logout')
        .then(res => {
          if(res.code == 0){
            sessionStorage.clear();
            this.$router.push({name:'login'})
          }
        })
        .catch(e => {
          console.log(e);
          // this.$Message.error(res.msg);
        })
        //localStorage.clear();
        //this.$router.push({name:'login'})
      },
      collapsedSider () {
        this.$refs.sideLeft.toggleCollapse();
        this.showLogo = !this.showLogo;
      },
      linkPage (url) {
       // console.log(url)
        this.$router.push({path:url})
      },
     toYuan(money){
      if(money){
        return (money/100).toFixed(2)
      }else{
        return 0
      }
     },
    resetValidate(name) {
      this.$refs[name].resetFields();
    },
    handleUpload(file){
      console.log(file,'file');
      // this.file = file;
      return true;
    },
    handleSuccess (res, file) {
      console.log(res,'res')
      this.formRole.image = res.data.url;
      this.imageUrl =  res.data.url;
      // console.log(this.formRole.image);
      this.$refs.formRole.validateField('image');
      this.$Message.success('上传成功')
    },
    handleError(error){
      console.log(error,'error');
    },
    submitModal(){
      this.$refs.formRole.validate((valid) => {
        if(valid){
          let data = {
            amount:this.formRole.amount,
            image:this.formRole.image,
            bank_card:this.formRole.bank_card,
            company:this.formRole.company
          }
          this.$post('/merchant/pay',data).then(res => {
            console.log(res,'充值');
            if(res.code == 0){
              // this.$Message.success(res.msg);
                this.show = false;
                this.imageUrl='';
                this.resetValidate('formRole');
                this.formRole.bank_card = '';
                this.formRole.company = '';
                this.formRole.amount = '';
                this.$Message.success("充值完成");
                this.getList(this.url)
            }else{
              this.$Message.error(res.msg);
              this.show = false;
              this.resetValidate('formRole');
            }
          })

        }
      })
    },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .demo-spin-col{
        height: 100px;
        position: relative;
        border: 1px solid #eee;
    }
  /deep/ .list-btn .ivu-input-wrapper,.list-btn .ivu-btn-primary{
    margin: 3px;
  }
  /deep/  .list-btn .ivu-date-picker{
    margin-right: 3px;
  }

  .layout{
    background: #f5f7f9;
    position: relative;
    overflow: hidden;
    height: 100%;
  }
  .ivu-layout{
    height: 100%;
  }
  .menu-icon{
    transition: all .3s;
  }
  .menu-item span{
    display: inline-block;
    overflow: hidden;
    width: 70%;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
    transition: width .2s ease .2s;
  }
  .menu-item i{
    transform: translateX(0px);
    transition: font-size .2s ease, transform .2s ease;
    vertical-align: middle;
    font-size: 16px;
  }
  .collapsed-menu i{
    transform: translateX(5px);
    transition: font-size .2s ease .2s, transform .2s ease .2s;
    vertical-align: middle;
    font-size: 22px;
  }
  .ivu-layout-sider-children .ivu-menu{
    height: 100%;
    overflow-y: scroll;
  }
  .collapsed-menu .menu-item-title{
    display: none;
    transition: all .2s ease;
  }
  .ivu-layout-header{
    padding: 0;
    line-height: 0;
    height:89px;
  }
  .ivu-menu-horizontal{
    height: 50px;
    line-height: 50px;
  }
  .collapse-btn{
    float: left;
    color: #eee;
  }
  .rotate-icon{
    transform: rotate(-90deg);
  }
  .layout-nav{
    float: right;
  }
  .ivu-menu-item>i,.ivu-menu-submenu-title>i{
    margin: 0;
  }
  .ivu-layout-content{
    overflow-y: auto;
  }
  .tag-nav-wrapper {
    background: #f0f0f0;
    height: 40px;
    overflow: hidden;
    padding: 0;
  }

  .dropdown-hide{
    position: absolute;
    top: 18px;
    z-index: -1;
  }
  .dropdown-show{
    z-index: 2000;
    transition: all .2s ease .5s;
  }

  .dropdown-hide a .ivu-icon{
    opacity: 0;
  }

  .dropdown-hide a .ivu-icon:hover{
    color: #fff;
    opacity: 1;
  }

  .ivu-dropdown{
    display: block;
  }

  .ivu-menu-dark.ivu-menu-vertical .ivu-menu-item-active:not(.ivu-menu-submenu){
    background: none;
    color: rgba(255,255,255,0.7);
  }

  .ivu-menu-dark.ivu-menu-vertical .ivu-menu-item-active:not(.ivu-menu-submenu):hover{
    color: rgba(255,255,255,1);
  }

  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  .ivu-menu::-webkit-scrollbar{
    width: 1px;  /*滚动条宽度*/
    height: 1px;  /*滚动条高度*/
  }

  /*定义滚动条轨道 内阴影+圆角*/
  .ivu-menu::-webkit-scrollbar-track{
    border-radius: 2.5px;  /*滚动条的背景区域的圆角*/
    background-color: #515a6e;/*滚动条的背景颜色*/
  }

  /*定义滑块 内阴影+圆角*/
  .ivu-menu::-webkit-scrollbar-thumb {
    border-radius: 2.5px;  /*滚动条的圆角*/
    background-color: #515a6e;  /*滚动条的背景颜色*/
  }
   /deep/ .ivu-upload.ivu-upload-select{
  .picture {
    width: 300px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    display: inline-block;
    border:1px dashed #eaeaea;
  }
  .avatar, .avatar-uploader{
    width:100%;
    height:100%;
  }
}
.activeRest{
  color:#FC6665;
}

</style>
